package xin.xihc.jba.core.bean;

import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import xin.xihc.jba.annotation.JsonHandler;
import xin.xihc.jba.core.utils.FieldCache;
import xin.xihc.utils.json.JsonUtil;

import java.lang.reflect.Field;
import java.sql.Types;

/**
 * 增加对java枚举类型的支持
 *
 * @author Leo.Xi
 * @date 2018年5月2日
 */
public class JbaBeanProperty extends BeanPropertySqlParameterSource {

    /** 当前实体的类型 */
    private Class<?> clazz;

    public JbaBeanProperty(Object object) {
        super(object);
        clazz = object.getClass();
    }

    @Override
    public int getSqlType(String paramName) {
        int sqlType = super.getSqlType(paramName);
        if (sqlType == TYPE_UNKNOWN && hasValue(paramName)) {
            if (null != getValue(paramName) && getValue(paramName).getClass().isEnum()) {
                sqlType = Types.VARCHAR;
                this.registerSqlType(paramName, sqlType);
            }
        }
        return sqlType;
    }

    @Override
    public Object getValue(String paramName) {
        Object value = super.getValue(paramName);
        if (value != null) {
            Field field = FieldCache.getField(clazz, paramName);
            JsonHandler toJson = field.getAnnotation(JsonHandler.class);
            // 非java自身对象、数组的、集合的直接转为json字符串
            if (toJson != null) {
                return JsonUtil.toNoNullJsonStr(value, false);
            }
        }
        return value;
    }

}
